package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-02-19
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private ProductDetailsMapper productDetailsMapper;
    @Autowired
    private SkuStockMapper skuStockMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Product> selectProductList() {
        return  baseMapper.selectProductList();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertProduct(Product product) {
        baseMapper.insert(product);
        List<ProductSku> productSkuList = product.getProductSkuList();
        for (int i = 0; i < productSkuList.size(); i++){
            ProductSku productSku = productSkuList.get(i);
            productSku.setProductId(product.getId());
            productSku.setSkuCode(product.getId()+"-"+i);
            String skuName = product.getName()+"-"+productSkuList.get(i).getSkuSpec();
            productSku.setSkuName(skuName);
            productSku.setStatus(0);
            productSkuMapper.insert(productSku);

            //添加商品库存
            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStock.setCreateBy(SecurityUtils.getUsername());
            skuStock.setStatus(0);
            skuStockMapper.insert(skuStock);
        }
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(product.getId());
        productDetails.setImageUrls(String.join(",",product.getDetailsImageUrlList()));
        productDetailsMapper.insert(productDetails);
        return 1;
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setId(id);
        product.setStatus(status);
        baseMapper.updateById(product);

        //更细sku的状态
        productSkuMapper.update(
                null
                ,new LambdaUpdateWrapper<ProductSku>()
                        .eq(ProductSku::getProductId,id)
                        .set(ProductSku::getStatus,status)
        );
        String key = "product:sku:data";
        List<ProductSku> productSkuList = productSkuMapper.selectList(
                new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));

        if (status == 1) {
            // 商品上架时，将 sku ID 列表放入 bitmap
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), true);
            });
        } else if (status == -1) {
            // 商品下架时，将 sku ID 列表从 bitmap 中移除
            productSkuList.forEach(item -> {
                redisTemplate.opsForValue().setBit(key, item.getId(), false);
            });
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteProductByIds(List<Long> ids) {
        //删除商品
        baseMapper.deleteBatchIds(ids);
        //查询skuIds
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<ProductSku>()
                .in(ProductSku::getProductId, ids)
                .select(ProductSku::getId);
        List<ProductSku> productSkuList = productSkuMapper.selectList(queryWrapper);
        List<Long> skuIds = productSkuList.stream().map(ProductSku::getId).toList();

        //删除商品sku
        productSkuMapper.delete(new LambdaQueryWrapper<ProductSku>()
                .in(ProductSku::getProductId, ids));
        //删除商品详情
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>()
                .in(ProductDetails::getProductId, ids));
        //删除商品库存
        return skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>()
                .in(SkuStock::getSkuId, skuIds));
    }
}
